﻿using SqlSugar;
using System;
using System.Linq;

namespace HongYeSystemWebApi.Templet.Service
{
    public interface IHelpDB
    {
        SqlSugarClient OpenDB();
    }
    /// <summary>
    /// 数据库访问层 
    /// </summary>
    public class HelpDB : IHelpDB
    {
        public SqlSugarClient OpenDB()
        {
            SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = SConfigure.SDBConnString,
                DbType = DbType.MySql,
                InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
                IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样
               
            });
           //用来打印Sql方便调式
           Db.Aop.OnLogExecuting = (sql, pars) =>
           {
               Console.WriteLine(sql + "\r\n" +
               Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
           };
            //ERROR信息
            Db.Aop.OnError = (res) => {
                Console.WriteLine( "ERROR:\r\n" +res);
            };
            return Db;
        }
    }
    #region 测试Sugar 仓储模式
    //public class Account:HelpDB 
    //{
    //    //SqlSugarClient _db;
    //    //public Account(SqlSugarClient db)
    //    //{
    //    //    _db = db;
    //    //}

    //    public SimpleClient<HongYeSystemWebApi.Entity.Account> AccountDb { get { return new SimpleClient<Entity.Account>(OpenDB()); } }


    //    public string GetAccountAndRequest()
    //    {
    //        var result= OpenDB().Queryable<HongYeSystemWebApi.Entity.Account, HongYeSystemWebApi.Entity.RequestInfo>((a, ri) => new object[] {
    //            JoinType.Left,a.Description==ri.Url

    //        }).Select((a,ri)=> new { a,ri }).ToJson();
    //        return result;
    //    }
    //    //public T GetAccountAndRequest()
    //    //{

    //    //}

    //}
    #endregion
}
